import {useSelector,useDispatch} from 'react-redux';
import {useState} from 'react';
import {addTodo,toggleTodo } from './toolkit/todosSlice';
function ToolkitApp(){
    //使用状态选择器，从总状态选择一个状态切片出来,得到todos的数组
    const  todos= useSelector(state=>state.todos);
    //调用useDispatch获取store.dispatch
    const dispatch = useDispatch();
    //当改变了复选框的时候执行此函数，参数是改变的todo的id
    const handleToggleTodo = (id)=>{
        //调用addTodo方法返回一个action对象 {type:'toggleTodo',payload:id}
        let action = toggleTodo(id);
        //调用store.dispatch派发给仓库
        dispatch(action);
    }
    const handleAddTodo = (text)=>{
        const action = addTodo({text});//{type:'addTodo',payload:{text}}
        dispatch(action);
    }
    return (
        <>
          <h1>Todos</h1>
          <AddTodo handleAddTodo={handleAddTodo}/>
          <TodoList todos={todos} handleToggleTodo={handleToggleTodo}/>
        </>
    )
}
function AddTodo({handleAddTodo}){
    const [text,setText] = useState('');
    const handleSubmit = (event)=>{
        event.preventDefault();//阻止默认事件，不让页面刷新
        handleAddTodo(text);
        setText('');
    }
    return (
        <form onSubmit={handleSubmit}>
            <input value={text} onChange={(event)=>setText(event.target.value)}/>
            <input type="submit"/>
        </form>
    )
}
function TodoList({todos,handleToggleTodo}){
    return (
        <ul>
            {
                todos.map((todo)=>(
                    <li key={todo.id}>
                        <input 
                        type="checkbox" 
                        checked={todo.completed} 
                        onChange={()=>handleToggleTodo(todo.id)}/>
                        <span style={{textDecoration:todo.completed?'line-through':'none'}}
                        >{todo.text}</span>
                    </li>
                ))
            }
        </ul>
    )
}
export default ToolkitApp;